package com.siyoumi.app.modules.sh.admin;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.siyoumi.app.entity.ShCmd;
import com.siyoumi.app.modules.sh.entity.EnumShCmdRun;
import com.siyoumi.app.modules.sh.service.SvcShCmd;
import com.siyoumi.component.XBean;
import com.siyoumi.component.http.InputData;
import com.siyoumi.controller.AdminApiController;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.mybatispuls.JoinWrapperPlus;
import com.siyoumi.util.IEnum;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/xadmin/sh/sh__cmd__list")
public class sh__cmd__list
        extends AdminApiController {
    @GetMapping()
    public XReturn index() {
        setPageTitle("执行脚本列表");

        InputData inputData = InputData.fromRequest();

        JoinWrapperPlus<ShCmd> query = SvcShCmd.getBean().listQuery(inputData);

        IPage<ShCmd> page = new Page<>(inputData.getPageIndex(), inputData.getPageSize());
        //list
        IPage<Map<String, Object>> pageData = SvcShCmd.getApp().getMaps(page, query);
        List<Map<String, Object>> list = pageData.getRecords();
        long count = pageData.getTotal();

        for (Map<String, Object> item : list) {
            ShCmd entity = XBean.fromMap(item, ShCmd.class);

            item.put("id", entity.getKey());

            //运行状态
            String run = IEnum.getEnmuVal(EnumShCmdRun.class, entity.getScmd_run());
            item.put("run", run);
        }

        getR().setData("list", list);
        getR().setData("count", count);

        return getR();
    }


    //删除
    @Transactional
    @PostMapping("/del")
    public XReturn del() {
        return SvcShCmd.getBean().delete(getIds());
    }

    //重新运行
    @GetMapping("/reset")
    public XReturn reset() {
        if (XStr.isNullOrEmpty(getID())) {
            return EnumSys.MISS_VAL.getR("miss id");
        }

        ShCmd entity = SvcShCmd.getApp().getEntity(getID());
        if (entity == null) {
            return EnumSys.ERR_VAL.getR("id 异常");
        }
        if (entity.getScmd_run() == 0) {
            return XReturn.getR(20078, "脚本已是待运行");
        }

        return SvcShCmd.getBean().setRun(getID(), 0);
    }
}
